<!-- 策划案例详情 -->
<!-- from 查看设计策划书 @/views/design/projectDesignManage/add -->
<template>
  <base-breadcrumb>
    <a-card :bordered="false" style="over-flow:scroll">
      <title-name v-if="type == 'view'" title="查看策划案例详情" />
      <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }">
        <a-row>
          <a-col :md="16" :sm="16">
            <a-form-model-item label="所属单位" :label-col="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }" prop="projectId">
              <org-tree-select
                v-model="form.projectId"
                is-special-tree
                is-need-auth
                is-auto-select-first
                :is-query-projec-detail="false"
                check-strictly
                :disabled="type == 'view'"
                :status-set="type == 'view' ? [1, 2, 3, 4, 5, 6] : [1, 2, 3]"
                :extra-query="{
                  auditStatus: 2,
                  ifDesignPlanBook: 1
                }"
                :excludeBusinessSet="type !== 'add' ? [$route.query.id] : []"
                :extra-tree-data="extraTreeData"
                @select="selectOrg"
              />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="项目设计管理类别" prop="designType">
              <BaseInput v-model="form.designType" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="设计策划书名称" prop="name">
              <BaseInput v-model="name" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="双优化立项计划表" prop="optimization">
              <BaseInput v-model="form.optimization" disabled />
            </a-form-model-item>
          </a-col>
          <a-button v-if="type == 'view'" type="primary" style="margin-left:20px" @click="openToTable">
            查看
          </a-button>
        </a-row>
        <a-row>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="创建人" prop="person">
              <BaseInput v-model="form.person" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="创建时间" prop="user">
              <BaseInput v-model="form.time" disabled placeholder="请输入" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <title-name v-if="type == 'view'" title="设计策划书/盈亏分析表" />
      <title-name v-else title="上传设计策划书/盈亏分析表" />
      <a-button :disabled="selectedRowKeys.length == 0 || spinning" type="primary" style="margin-bottom: 20px;margin-left: 20px" @click="downZip([{ fileInfoList: selectedRows }])">
        选中导出
      </a-button>
      <a-table :loading="loadingState.isUpload" row-key="commonId" bordered :columns="columnAssment" :data-source="dataAssement" :row-selection="rowSelection">
        <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span
        ><span slot="action" slot-scope="text, record, index">
          <a :href="'/api/ycloud-file-center/oper/download?access_token=' + token + '&fileId=' + record.fileId" target="_parent">导出</a>
          <a-divider type="vertical" />
          <a href="javascript:" @click="$filePreview(record)">预览</a>
        </span>
      </a-table>
    </a-card>
    <a-modal title="关联双优化立项计划表" :visible="visible" :confirm-loading="confirmLoading" width="1000px" @ok="handleOk" @cancel="handleCancel">
      <a-form>
        <title-name title="双优化立项计划基本信息" />
        <a-row>
          <a-col :md="12" :sm="12">
            <a-form-model-item label="双优化立项计划表" :label-col="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }">
              <BaseInput v-model="formAdd.name" disabled />
            </a-form-model-item>
          </a-col>

          <a-col :md="12" :sm="12">
            <a-form-model-item label="分公司" :label-col="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }">
              <BaseInput v-model="formAdd.branchOffice" disabled itemtype="" />
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="12">
            <a-form-model-item label="项目" :label-col="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }">
              <BaseInput v-model="formAdd.project" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="12">
            <a-form-model-item label="创建人" :label-col="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }">
              <BaseInput v-model="formAdd.filledBy" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="12">
            <a-form-model-item label="编制时间" :label-col="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }">
              <BaseInput v-model="formAdd.createTime" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="12">
            <a-form-model-item label="状态" :label-col="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }">
              <BaseInput v-model="formAdd.chiStatus" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form>

      <title-name title="计划项信息" />
      <a-table :columns="columns" :data-source="tableData">
        <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
      </a-table>
    </a-modal>
    <div class="footer page-btn-right-top">
      <a-button type="primary" @click="goBack">关闭</a-button>
    </div>
    <selectApprover :business-id="businessId" :process-config="setProcessConfig" />
  </base-breadcrumb>
</template>

<script>
import Vue from 'vue'
import BasePage from '@/views/basePage'
import { getProjectType } from '@/api/design/plotsPlan'
import { planList } from '@/api/technical/optimizationPlan'
import { getplotsManageEdit, getplotsManageDetail, getplotsManageAdd } from '@/api/design/designManage'
import { uploadFile, deleteUploadFile } from '@/api'
import { getAuditProject, getCurrentUserBranchCom } from '@/api/themeChoose/themeChoose'
import debounce from 'lodash/debounce'

const columns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '双优化名称',
    dataIndex: 'name'
  },
  {
    title: '双优化分类',
    dataIndex: 'categoryName'
  },
  {
    title: '详细类型',
    dataIndex: 'detailedCategoryName'
  },
  {
    title: '内容描述',
    dataIndex: 'content'
  },
  {
    title: '技术实施时间',
    dataIndex: 'startTime'
  },
  {
    title: '提出人',
    dataIndex: 'proposer'
  },
  {
    title: '拟实施人',
    dataIndex: 'implement'
  },
  {
    title: '预测效益(万)',
    dataIndex: 'benefit'
  }
]
const columnAssment = [
  {
    title: '序号',
    dataIndex: 'serial',
    width: '5%',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '附件名称',
    dataIndex: 'fileName',
    width: '35%'
  },
  {
    title: '附件格式',
    dataIndex: 'suffixName',
    width: '35%'
  },
  {
    title: '操作',
    key: 'action',
    width: '20%',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'KnowledgeBasePlanDetail',
  extends: new BasePage(),
  components: {},
  data() {
    // this.searchArr = searchArr
    this.columns = columns
    return {
      loadingState: {
        isUpload: false,
        isDraft: false,
        isSubmit: false
      },
      form: {
        designType: '',
        time: this.getNowTime(),
        name: ''
      },
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return planList(requestParameters).then(res => {
          return res
        })
      },
      selectedRowKeys: [],
      loading: false,
      selectedRows: [],
      fileArrysDataList: [],
      formAdd: {
        time: this.getNowTime(),
        person: ''
      },
      tableData: [],
      confirmLoading: false,
      disabled: false,
      type: '',
      id: '',
      columnAssment,
      dataAssement: [],
      uploadFile: {},
      deleteObj: {},
      token: '',
      fileFileds: null,
      branchCompanyLists: [],
      fileIds: [],
      // 附件上传
      listUrl: '',
      deleteUrl: '/cscec-project-business/file/business/project-fileDelete',
      uploadList: '',
      businessId: '',
      businessCode: 'PM25',
      uploadArrys: [],
      designType: '',
      reqMethod: 'post',
      projectLists: [],
      name: '',
      status: '',
      pageType: '',
      jobsList: [],
      visible: false,
      user: '',
      rules: {
        // optimization: [{ required: true, message: '请关联双优化立项计划表', trigger: 'change' }],
        branchId: [{ required: true, message: '请选择单位名称', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }]
      },
      // 文件列表
      files: [],
      // 一次最多10个
      num: 10,
      // 可上传数量
      count: 100,
      //上传loading
      spinning: false,
      // 多文件上传
      multiple: true,
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      extraTreeData: []
    }
  },
  computed: {
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
          let fileFileds = []
          let fileIds = []
          selectedRows.forEach(function(obj, i) {
            fileFileds.push(obj.fileId)
            fileIds.push(obj.commonId)
          })
          this.fileFileds = fileFileds.join(',') // 删除公共附件
          this.fileIds = fileIds // 有业务id 删除附件
        }
      }
    }
  },
  async created() {
    // 获取登录人名称
    this.form.person = JSON.parse(sessionStorage.getItem('ycloud-user_info')).employee.name
    this.type = this.$route.query.type
    this.id = this.$route.query.id
    // this.getCurrentUserBranchCom()
    if (this.type == 'edit' || this.type == 'view') {
      // this.changeProjectType()
      this.getplotsManageDetail()
    }
    this.token = Vue.getAcloudProvider().getAccessToken()
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('project_design_proposal')
  },
  methods: {
    selectOrg(val) {
      if (val.length > 1) {
        this.form.branchId = val[val.length - 2].orgId
        this.changeProjectType()
      }
    },
    openToTable() {
      this.planList()
    },
    getCurrentUserBranchCom() {
      this.loading = true
      getCurrentUserBranchCom({ tagCodes: ['BC'] }).then(res => {
        this.branchCompanyLists = res.data
        if (this.type == 'add') {
          this.$set(this.form, 'branchId', this.branchCompanyLists[0].orgId)
          if (this.form.branchId) {
            getAuditProject({ branchComIds: [this.form.branchId], ifDesignPlanBook: 0, auditStatus: 2 }).then(res => {
              this.projectLists = res.data

              this.$set(this.form, 'projectId', this.projectLists[0].projectId)
              this.$set(this.form, 'designType', this.projectLists[0].designTypeName)
              let name = this.projectLists[0].projectName + '设计策划书'
              this.$set(this, 'name', name)
            })
          }
        }
        this.loading = false
      })
    },
    getplotsManageDetail() {
      if (this.id) {
        getplotsManageDetail({ id: this.id }).then(res => {
          this.form = res.data
          this.name = res.data.name
          this.form.branchId = res.data.branchCompanyId
          this.dataAssement = res.data.fileIdsInfo
          const arr = [
            {
              orgId: res.data.branchCompanyId,
              orgName: res.data.branchCompany
            },
            {
              orgId: res.data.projectId,
              orgName: res.data.project,
              projectId: res.data.projectId,
              projectName: res.data.project
            }
          ]
          this.extraTreeData = arr
          // getAuditProject({ branchComIds: [this.form.branchId], ifDesignPlanBook: 0, auditStatus: 2 }).then((res) => {
          //   this.projectLists = res.data
          //   let arr = {}
          //   arr = {
          //     projectId: this.form.projectId,
          //     designTypeId: this.form.designTypeId,
          //     designTypeName: this.form.designType,
          //     projectName: this.form.project
          //   }
          //   this.projectLists.push(arr)
          // })
        })
      }
    },
    planList() {
      if (this.form.projectId) {
        planList({ pageSize: 10, pageNo: 1, query: { project: this.form.projectId, status: 2 } }).then(res => {
          if (!res.data || res.data == [] || !res.data[0]) {
            this.$message.error('该项目还没有生成双优化立项计划表')
            this.visible = false
          } else {
            this.visible = true
            this.tableData = res.data[0].doubleOptimizationTypeVO
            this.formAdd = res.data[0]
          }
        })
      } else {
        this.$message.error('请先选择要关联的项目')
      }
    },
    fileArrysData(val) {
      this.fileArrysDataList = val
    },

    getPopupContainer(triggerNode) {
      return triggerNode.parentNode
    },
    deleteExteriorFile() {
      let that = this
      if (that.selectedRowKeys.length == 0) {
        that.$message.error('请先选中需要删除的附件！')
        return
      }
      if (that.id) {
        that.$confirm({
          title: '删除',
          content: '确定删除附件吗？',
          onOk() {
            that.dataAssement = that.dataAssement.filter(item => {
              return !that.fileIds.includes(item.commonId)
            })
            let arr = []
            that.dataAssement.forEach(function(obj, i) {
              arr.push(obj.commonId)
            })
            that.form.fileIds = arr

            that.selectedRowKeys = []
            that.selectedRows = []
            that.$message.success('删除成功')
          },
          onCancel() {}
        })
      } else {
        that.$confirm({
          title: '删除',
          content: '确定删除附件吗？',
          onOk() {
            that.loadingState.isUpload = true
            deleteUploadFile({ fileIds: that.fileFileds })
              .then(res => {
                that.loadingState.isUpload = false
                if (res.code == '0' || res.data.code == '0') {
                  let data = that.dataAssement
                  let selectDatas = that.fileIds
                  that.dataAssement = data.filter(item => {
                    return !selectDatas.includes(item.commonId)
                  })
                  that.selectedRowKeys = []
                  that.selectedRows = []
                  that.$message.success('删除成功')
                }
              })
              .catch(() => {
                that.loadingState.isUpload = false
              })
          },
          onCancel() {}
        })
      }
    },
    /**
     * @description: 500M提示
     * @param {void}
     * @return {function}
     */
    sizeDebounce: debounce(function() {
      this.$message.error('上传文件不可超出500M')
    }, 500),
    // 上传
    beforeUpload(info) {
      // this.uploadFile = info
      return false
    },
    /**
     * @description: 文件上传防抖
     * @param {function}
     * @return {void}
     */
    fileChange: debounce(function() {
      this.handleUploadFun()
    }, 500),
    /**
     * @description: 接管文件上传
     * @param {object} info 文件对象
     * @return {void}
     */
    handleChanges(info) {
      let pass = true
      const { file } = info
      if (file.size / 1024 / 1024 > 500) {
        // 附件大小校验
        // 限制文件大小为500M
        this.sizeDebounce()
        pass = false
      }
      if (pass) {
        this.files.push(file)
        this.fileChange()
      }
    },
    /**
     * @description: 判断及操作上传文件队列
     * @return {void}
     */
    async handleUploadFun() {
      let pass = true
      if (pass && this.dataAssement.length + this.files.length > this.count) {
        pass = false
        this.$message.error(`最多上传${this.count}个文件！`)
        this.files = this.files.slice(0, this.count - this.dataAssement.length)
      }
      if (this.multiple) {
        if (pass && this.files.length > this.num) {
          this.$message.error(`一次最多上传${this.num}个文件！`)
          this.files = this.files.slice(0, this.num)
        }
      }
      this.spinning = true
      // 防止上传错误一直loading
      try {
        for (let i = 0; i < this.files.length; i++) {
          await this.uploadFun(this.files[i])
        }
      } catch (err) {
        console.log(err)
      } finally {
        this.files = []
        this.spinning = false
      }
    },
    /**
     * @description: 上传函数拆分
     * @param {FormData} data
     * @return {void}
     */
    uploadFun(info) {
      return new Promise(async (resolve, reject) => {
        const data = new FormData()
        data.append('file', info)
        data.append('businessCode', this.businessCode)
        let arr = []
        this.loadingState.isUpload = true
        uploadFile(data)
          .then(res => {
            this.loadingState.isUpload = false
            if (res.code === 200) {
              arr.push(res.data)
              if (this.dataAssement != null) {
                this.dataAssement = arr.concat(this.dataAssement)
              } else {
                this.dataAssement = arr
              }

              let commomIds = []
              this.dataAssement.forEach(function(obj, i) {
                commomIds.push(obj.commonId)
              })
              this.form.fileIds = commomIds
              this.selectedRowKeys = []
              this.selectedRows = []
            }
            resolve()
          })
          .catch(() => {
            this.loadingState.isUpload = false
            reject()
          })
      })
    },
    saveForm() {
      let that = this
      that.form.name = that.name
      that.form.project = null

      that.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (that.form.designType == '' || that.form.designType == null) {
            that.$message.error('请先设计项目管理类别！')
            return
          }
          if (that.loadingState.isDraft) {
            return
          }
          that.loadingState.isDraft = true
          if (that.id) {
            try {
              that.form.status = '0'
              if (that.form.fileIdsInfo != null) {
                let arr = that.dataAssement
                let commonIds = []
                if (arr.length > 0) {
                  arr.forEach(function(obj, i) {
                    commonIds.push(obj.commonId)
                  })
                }
                let newArr = [...new Set(commonIds)]
                that.form.fileIds = newArr
              }
              getplotsManageEdit(that.form)
                .then(res => {
                  that.loadingState.isDraft = false
                  if (res.data.code == 200 || res.code == 200) {
                    that.$multiTab.close(this.$route.fullpath)
                    that.$message.success('保存成功')
                  }
                })
                .catch(() => {
                  that.loadingState.isDraft = false
                })
            } catch (e) {
              console.error(e)
              that.loadingState.isDraft = false
            }
          } else {
            this.form.status = '0'
            getplotsManageAdd(this.form)
              .then(res => {
                that.loadingState.isDraft = false
                if (res.data.code == 200 || res.code == 200) {
                  that.$multiTab.close(this.$route.fullpath)
                  that.$message.success('保存成功')
                }
              })
              .catch(() => {
                that.loadingState.isDraft = false
              })
          }
          // }
        }
      })
    },
    saveSubmit() {
      let that = this
      that.setProcessConfig = null
      that.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (that.form.designType == '' || that.form.designType == null) {
            that.$message.error('请先设计项目管理类别！')
            return
          }

          that.form.name = that.name
          if (that.loadingState.isSubmit) {
            return
          }
          that.loadingState.isSubmit = true
          // if(!that.form.optimization){
          if (false) {
            planList({ pageSize: 10, pageNo: 1, query: { project: that.form.projectId } })
              .then(res => {
                that.loadingState.isSubmit = false
                if (res.data && res.data.length !== 0) {
                  that.$message.error('请选择关联双优化立项计划表')
                  return false
                } else {
                  that.$message.error('请选择双优化立项计划表')
                  return false
                }
              })
              .catch(() => {
                that.loadingState.isSubmit = false
              })
          } else {
            if (that.id) {
              try {
                that.form.status = '1'
                if (that.form.fileIdsInfo != null) {
                  let arr = that.dataAssement
                  let commonIds = []
                  if (arr.length > 0) {
                    arr.forEach(function(obj, i) {
                      commonIds.push(obj.commonId)
                    })
                  }
                  let newArr = [...new Set(commonIds)]
                  that.form.fileIds = newArr
                }
                getplotsManageEdit(that.form)
                  .then(res => {
                    that.loadingState.isSubmit = false
                    if (res.data.code == 200 || res.code == 200) {
                      that.$message.success('提交成功')
                      //提交时，返回id
                      that.businessId = res.data.message || that.id
                      that.setProcessConfig = that.processConfig
                    }
                  })
                  .catch(() => {
                    that.loadingState.isSubmit = false
                  })
              } catch (e) {
                console.error(e)
                that.loadingState.isSubmit = false
              }
            } else {
              this.form.status = '1'
              getplotsManageAdd(this.form)
                .then(res => {
                  that.loadingState.isSubmit = false
                  if (res.data.code == 200 || res.code == 200) {
                    that.$message.success('提交成功')
                    //提交时，返回id
                    that.businessId = res.data
                    that.setProcessConfig = that.processConfig
                  }
                })
                .catch(() => {
                  that.loadingState.isSubmit = false
                })
            }
          }
        }
      })
    },
    goBack() {
      this.$multiTab.close(this.$route.fullpath)
    },
    handleChangeCompany(value) {
      if (this.form.branchId) {
        getAuditProject({ branchComIds: [this.form.branchId], ifDesignPlanBook: 0, auditStatus: 2 }).then(res => {
          this.projectLists = res.data

          this.$set(this.form, 'projectId', '')
          // this.$set(this.form, 'designType', this.projectLists[0].designTypeName)
          // this.$set(this.name, 'name', this.projectLists[0].projectName +'设计策划书')
        })
      }
    },
    changeProjectType() {
      if (this.type !== 'view') {
        this.$set(this.form, 'optimization', '')
        this.$set(this.form, 'optimizationId', '')
      }
      let arr = []
      arr.push(this.form.projectId)
      getProjectType({ projectIds: arr }).then(res => {
        this.form.num = res.data[0].projectNumber
        this.form.designType = res.data[0].designTypeName
        this.form.designTypeId = res.data[0].designTypeId
        this.name = res.data[0].name + '设计策划书'
        // this.$set(this.form, 'projectId', res.data[0].projectId)
        this.$set(this.form, 'designType', res.data[0].designTypeName)
        // this.$set(this.name, 'name', res.data[0].projectName + '设计策划书')
      })
    },

    search(values) {
      this.queryParam = values
      this.$refs.table.refresh(true)
    },
    goAdd() {
      // this.visible = true
    },
    handleSub(record, type) {
      this.visible = true
      this.type = type
      this.form = record
    },
    handleEdit(record) {
      this.visible = true
      this.form = record
    },
    handleOk() {
      this.visible = false
      this.form.optimization = this.formAdd.name
      this.form.optimizationId = this.formAdd.id
    },
    handleCancel() {
      this.visible = false
    }
  }
}
</script>

<style scoped>
.input {
  width: 100%;
}
.footer {
  float: right;
  margin-right: 10px;
}
.footer button {
  margin-left: 10px;
}
</style>
